package com.rxmvp.rxmvpdemo.RxRetrofit;


import com.trello.rxlifecycle.ActivityEvent;
import com.trello.rxlifecycle.FragmentEvent;
import com.trello.rxlifecycle.components.ActivityLifecycleProvider;
import com.trello.rxlifecycle.components.FragmentLifecycleProvider;

import rx.Observable;

/**
 * 作者： huangRZ on 2017/1/21. 15:04
 * 邮箱：917647409@qq.com
 */
public class RxRetrofitUtils {

    private ActivityEvent mActivityEvent;
    private FragmentEvent mFragmentEvent;

    private static final Observable.Transformer baseTransformer = new BaseTransformer<>();

    @SuppressWarnings("unchecked")
    public <T> Observable<? extends T> getObservable(Observable<T> observable,
                                                     ActivityLifecycleProvider provider) {
        return observable
                .compose(mActivityEvent == null ? provider.<T>bindToLifecycle()
                        : provider.<T>bindUntilEvent(mActivityEvent)) //设置Subscriber跟随Activity的生命周期
                .compose(baseTransformer);
    }

    @SuppressWarnings("unchecked")
    public <T> Observable<? extends T> getObservable(Observable<T> observable,
                                                     FragmentLifecycleProvider provider) {
        return observable
                .compose(mFragmentEvent == null ? provider.<T>bindToLifecycle()
                        : provider.<T>bindUntilEvent(mFragmentEvent)) //设置Subscriber跟随Fragment的生命周期
                .compose(baseTransformer);
    }

    //设置在哪个生命周期发生时解绑，不设置默认跟随activity的生命周期
    public RxRetrofitUtils setLifecycleEvent(ActivityEvent activityEvent) {
        this.mActivityEvent = activityEvent;
        return this;
    }

    //设置在哪个生命周期发生时解绑，不设置默认跟随fragment的生命周期
    public RxRetrofitUtils setLifecycleEvent(FragmentEvent fragmentEvent) {
        this.mFragmentEvent = fragmentEvent;
        return this;
    }

}
